#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# expects the following variables defined in the environment:
# - GITLAB_PROJECT_URL: git repo without protocol
# - GITLAB_FORK_URL: fork of the git repo without protocol
# - GITLAB_TOKEN: GitLab private token with access to the git repo
# - BRANCH_NAME: branch name in the fork of the git repo
# - SOURCE_BRANCH_NAME: source branch name to checkout, by default `main`
# - REVIEWERS: users to notify in MR description: @reviewer1 @reviewer2
# - GIT_USER_NAME: Git user name
# - GIT_USER_EMAIL: Git user email

# shellcheck disable=SC1091
. cki_utils.sh

BASE_DIR=$(mktemp -d)
trap 'rm -rf "${BASE_DIR}"' EXIT

DATA_PATH="${BASE_DIR}/repo"
mkdir -p "${DATA_PATH}"
cd "${DATA_PATH}"

cki_echo_yellow "Fetching repository..."
if ! [[ -d .git ]]; then
    # shellcheck disable=SC2154
    git clone "https://ignored:${GITLAB_TOKEN}@${GITLAB_PROJECT_URL}.git/" .
    cki_echo_green "  successfully cloned main repository"
    # shellcheck disable=SC2154
    git remote add fork "https://ignored:${GITLAB_TOKEN}@${GITLAB_FORK_URL}.git/"
    # shellcheck disable=SC2154
    git config user.name "${GIT_USER_NAME}"
    # shellcheck disable=SC2154
    git config user.email "${GIT_USER_EMAIL}"
fi
git fetch --all
cki_echo_green "  successfully fetched updates"

# shellcheck disable=SC2154
cki_echo_yellow "Checking out '${BRANCH_NAME}'"
if git show-ref --verify --quiet "refs/remotes/fork/${BRANCH_NAME}"; then
    git switch --track "fork/${BRANCH_NAME}"
    git reset --hard "fork/${BRANCH_NAME}"
    cki_echo_green "  switched to branch"
    git rebase origin/HEAD
    cki_echo_green "  rebased to origin/HEAD"
else
    git checkout --track "origin/${SOURCE_BRANCH_NAME:-main}" -b "${BRANCH_NAME}"
    git config "branch.${BRANCH_NAME}.merge" "refs/heads/${BRANCH_NAME}"
    git config "branch.${BRANCH_NAME}.remote" fork
    cki_echo_green "  created branch"
fi

cki_echo_yellow "Generating CODEOWNERS"
python3 -m pip install --user git+https://gitlab.com/cki-project/kpet.git@production
git clone https://gitlab.com/redhat/centos-stream/tests/kernel/kpet-db.git --depth 1 --branch production
python3 -m kpet --db kpet-db test list -o json > kpet-db-tests.json
GITLAB_TOKENS='{"gitlab.com":"GITLAB_TOKEN"}' \
    python3 -m cki_tools.gitlab_codeowners_config \
    --test-path kpet-db-tests.json \
    update
cki_echo_green "  completed"

cki_echo_yellow "Checking for changes"
git add CODEOWNERS
if ! git diff --stat --cached --exit-code; then
    timestamp=$(date +'%F %H:%M')
    git commit -m "CODEOWNERS updates as of ${timestamp}"
    footer=$(python3 -m cki_lib.footer --format gitlab)
    # shellcheck disable=SC2154
    git push \
        --force \
        --push-option merge_request.create \
        --push-option merge_request.title="CODEOWNER updates" \
        --push-option merge_request.description="Updated CODEOWNERS with latest updates: ${REVIEWERS}${footer//$'\n'/'\n'}" \
        --push-option merge_request.remove_source_branch \
        fork
    cki_echo_green "  committed and pushed changes"
elif ! git log origin/"${BRANCH_NAME}" ^HEAD --quiet --exit-code; then
    cki_echo_green "  updating rebased branch"
    git push --force
else
    cki_echo_green "  no changes found"
fi
